package com.example.capsule_kafka.service;

import com.example.capsule_kafka.bean.ChatRecordBean;
import com.example.capsule_kafka.bean.UserInfoBean;
import com.example.capsule_kafka.global.GlobalThreadPool;
import com.example.capsule_kafka.impl.ChatRecordServiceImpl;
import com.example.capsule_kafka.mapper.UserInfoMapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;


/**
 * @Author: zhuzhiming
 * @Date: 2022/5/5 21:30
 */
@Service
@Slf4j
public class UserInfoService {


    @Resource
    UserInfoMapper userInfoMapper;

    @Autowired
    GroupMessageService groupMessageService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    ChatRecordServiceImpl chatRecordService;

    //TODO 更新单聊


    public void doUpdateUserInfo(UserInfoBean userInfoBean) {

        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                redisTemplate.delete(String.valueOf(userInfoBean.getId()));
            }
        });

        String currAvatarUrl = userInfoBean.getAvatarUrl();
        String currNickname = userInfoBean.getNickname();
        UserInfoBean queryInfo = userInfoMapper.selectById(userInfoBean.getId());

        if (!currNickname.equals(queryInfo.getNickname())) {
            GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    String fieldRecord = queryInfo.getFieldRecord();
                    String[] fields = fieldRecord.split(",");
                    for (String field : fields) {
                        if (chatRecordService.existIndex(field.toLowerCase())) {
                            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                            TermQueryBuilder query = QueryBuilders.termQuery("senderId", queryInfo.getId());
                            searchSourceBuilder.size(500);
                            searchSourceBuilder.query(query);
                            SearchResponse response = chatRecordService.search(field.toLowerCase(), searchSourceBuilder);
                            for (SearchHit hit : response.getHits()) {
                                chatRecordService.update(field.toLowerCase(), hit.getId(), userInfoBean.getNickname());
                            }
                        }
                    }

                }
            });
        }

        if (!currAvatarUrl.contains("/")) {
            userInfoBean.setAvatarServerPath("");
        } else if (queryInfo != null) {
            userInfoBean.setAvatarServerPath(queryInfo.getAvatarServerPath());
        }
        int mark = userInfoMapper.updateById(userInfoBean);
        if (mark == 1) {
            log.info("update user success");
            assert queryInfo != null;
            if (!queryInfo.getAvatarUrl().equals(currAvatarUrl) || !currNickname.equals(queryInfo.getNickname())){
                GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        groupMessageService.updateMessage(userInfoBean.getId(), userInfoBean.getAvatarUrl(), userInfoBean.getAvatarServerPath(),userInfoBean.getNickname());
                    }
                });
            }

        } else {
            log.warn("update user fail");
        }


    }


    public void doSaveUser(UserInfoBean userInfoBean) {
        userInfoMapper.insert(userInfoBean);
    }
}
